/**
 * 通义千问2.5-Omni API客户端
 */
import { QwenAPIConfig } from './config';
import { APIErrorHandler } from '../utils/errorHandler';
import { StreamResponse } from './streamResponse';
import { MultimodalInput, ChatMessage, ChatCompletionOptions } from '../interfaces/qwen';

/**
 * 通义千问API客户端
 */
export class QwenAPIClient {
  private apiKey: string;
  private baseURL: string;
  private errorHandler: APIErrorHandler;

  /**
   * 创建通义千问API客户端实例
   * @param apiKey API密钥
   * @param options 配置选项
   */
  constructor(apiKey: string, options: { baseURL?: string } = {}) {
    this.apiKey = apiKey;
    this.baseURL = options.baseURL || QwenAPIConfig.BASE_URL;
    this.errorHandler = new APIErrorHandler();
  }

  /**
   * 发送聊天请求
   * @param messages 对话消息历史
   * @param options 聊天选项
   * @returns 流式响应对象
   */
  async chatCompletion(
    messages: ChatMessage[],
    options: ChatCompletionOptions = {}
  ): Promise<StreamResponse> {
    const requestBody = QwenAPIConfig.buildChatRequestBody(messages, options);

    return this.errorHandler.executeWithRetry(() => 
      this.streamRequest({
        endpoint: QwenAPIConfig.CHAT_ENDPOINT,
        payload: requestBody
      })
    );
  }

  /**
   * 处理多模态输入
   * @param input 多模态输入数据
   * @param options 聊天选项
   * @returns 流式响应对象
   */
  async multimodalCompletion(
    input: MultimodalInput,
    chatHistory: ChatMessage[] = [],
    options: ChatCompletionOptions = {}
  ): Promise<StreamResponse> {
    const userMessage = QwenAPIConfig.formatMultimodalMessage(input);
    const messages = [...chatHistory, userMessage];
    
    return this.chatCompletion(messages, options);
  }

  /**
   * 发送流式请求
   * @param options 请求选项
   * @returns 流式响应对象
   */
  private async streamRequest(options: {
    endpoint: string;
    payload: any;
    headers?: Record<string, string>;
  }): Promise<StreamResponse> {
    const { endpoint, payload, headers = {} } = options;
    
    const response = await fetch(endpoint.startsWith('http') ? endpoint : `${this.baseURL}/${endpoint}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        ...headers
      },
      body: JSON.stringify(payload)
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${errorData.message || response.statusText}`);
    }
    
    if (!response.body) {
      throw new Error('Stream not supported');
    }
    
    return new StreamResponse(response.body);
  }
}